import React from 'react'
import { Navigate, Outlet, useLocation } from 'umi'
export default function Auth() {
    const isToken = localStorage.getItem('token');
    const currentUser = isToken ? JSON.parse(isToken as string)[0] : null;
    const { pathname } = useLocation();
    const newPathArray = (pathname as string).split('/');
    if (newPathArray.length >= 4) {
        if(!isNaN(parseInt(newPathArray[newPathArray.length - 1]))){
            newPathArray[newPathArray.length - 1] = ':id';
        }
        
    }
    const newpathName = newPathArray.join('/');
    // 判断跳转的路由在后台数据库中是否有 pagepermisson 和 routepermisson 字段
    const estimatePermission = () => {
        const childrenList=JSON.parse(localStorage.getItem('childrenList')as string); 
        const rightList=JSON.parse(localStorage.getItem('rightList')as string);
        const rightAndChildrenData=[...childrenList,...rightList]; 
        const findItem = (rightAndChildrenData as Array<any>).find(item => item.key === newpathName)
        return findItem?.pagepermisson || findItem?.routepermisson||pathname === '/' ? true : false
    }

    // 判断localStorage中个人信息，个人所属角色中是否有对应路由的路径信息
    const estimateRouteConfig = () => {
        if (!isToken) {
            return <Navigate to='/login'></Navigate>
        }
        const { role: { rights: { checked } } } = currentUser;
        const { role: { rights } } = currentUser;
        if (checked) {
            if (pathname === '/' && checked?.includes('/home')) {
                return <Navigate to='/home'></Navigate>
            }
            return checked?.includes(newpathName) ? <Outlet></Outlet> : <Navigate to='/404'></Navigate>
        }
        else {
            if (pathname === '/' && rights?.includes('/home')) {
                return <Navigate to='/home'></Navigate>
            }
            return rights?.includes(newpathName) ? <Outlet></Outlet> : <Navigate to='/404'></Navigate>
        }
    }

    return estimatePermission()?estimateRouteConfig():<Navigate to='/404'></Navigate>
}

